package com.itheima.app.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.autoconfig.AipFaceTemplate;
import com.itheima.autoconfig.OssTemplate;
import com.itheima.autoconfig.SmsTemplate;
import com.itheima.domain.db.User;
import com.itheima.domain.db.UserInfo;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.db.UserService;
import com.itheima.util.ConstantUtil;
import com.itheima.util.JwtUtil;
import com.itheima.vo.ErrorResult;
import com.itheima.vo.UserInfoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zsk
 * @create 2022-03-22-17:59
 */
@Component
public class UserManager {

    @DubboReference
    private UserService userService;

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @DubboReference
    private UserInfoService userInfoService;

    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    @Autowired
    private OssTemplate ossTemplate;

    //保存用户
    public ResponseEntity save(User user) {
        //保存
        Long userId = userService.save(user);
        //返回
        return ResponseEntity.ok(user);
    }

    // 查询用户
    public ResponseEntity findByPhone(String phone) {
        //调用service查询
        User user = userService.findByPhone(phone);

        //返回
        return ResponseEntity.ok(user);

    }

    //首次登录获取验证码
    public void sendSms(String phone) {

        //使用hootl工具包生成验证码
        String smsCode = RandomUtil.randomNumbers(6);

        smsCode = "123456";

        //调用阿里云发短信
//        smsTemplate.sendSms(phone,smsCode);//todo 前期测试写死，后期上线使用

        //将验证码存入Redis中，保存5分钟
        stringRedisTemplate.opsForValue().set(ConstantUtil.SMS_CODE + phone, smsCode, Duration.ofMinutes(5));

    }

    //登录与验证码校验
    public ResponseEntity loginVerification(String phone, String verificationCode) {

        //取出Redis中存储的验证码
        String redisCode = stringRedisTemplate.opsForValue().get(ConstantUtil.SMS_CODE + phone);

        //判断
        if (!StrUtil.equals(redisCode, verificationCode)) {
            //抛给前台错误
            return ResponseEntity.status(500).body(ErrorResult.sendSmsError());//验证码错误
        }

        //根据手机号查询用户
        User user = userService.findByPhone(phone);

        //查到了
        Boolean isNew;
        if (user != null) {//证明是老用户
            isNew = false;
        } else {//证明是新用户
            isNew = true;
            //补全参数
            user = new User();
            user.setMobile(phone);
            user.setPassword(ConstantUtil.INIT_PASSWORD);//初始化密码

            //保存新用户
            Long userId = userService.save(user);

            //设置主键id
            user.setId(userId);
        }

        //jwt制作令牌
        user.setPassword(null);//密码不希望前台知道
        Map<String, Object> claims = BeanUtil.beanToMap(user);
        String token = JwtUtil.createToken(claims);

        String json = JSON.toJSONString(user);
        //向Redis中保存，保存7天
        stringRedisTemplate.opsForValue().set(ConstantUtil.USER_TOKEN + token, json, Duration.ofDays(7));

        //返回结果
        Map map = new HashMap();
        map.put("token", token);
        map.put("isNew", isNew);
        return ResponseEntity.ok(map);
    }

    //首次登录补全信息
    public void loginReginfo(UserInfo userInfo, String token) {

        //解析token获取User对象
        User user = findUserByToken(token);
        userInfo.setId(user.getId());

        //调用rpc保存
        userInfoService.save(userInfo);
    }

    //解析token,获取User
    public User findUserByToken(String token) {
        //查看Redis是否存在token
        Boolean isCheck = stringRedisTemplate.hasKey(ConstantUtil.USER_TOKEN + token);
        //判断
        if (isCheck == true){//登录
            //获取用户信息
            String json = stringRedisTemplate.opsForValue().get(ConstantUtil.USER_TOKEN + token);
            //将json转换为User对象
            User user = JSON.parseObject(json, User.class);
            //续期7天
            stringRedisTemplate.opsForValue().set(ConstantUtil.USER_TOKEN + token,json,Duration.ofDays(7));
            //返回uese对象
            return user;

        }
        //没有token(未登录)返回null
        return null;

    }

    //首次登录完善用户头像信息
    public ResponseEntity loginReginfoHead(MultipartFile headPhoto, String token) throws Exception {

        //人脸检测
        boolean detect = aipFaceTemplate.detect(headPhoto.getBytes());
        if (detect == false){//非人像
            return ResponseEntity.status(500).body(ErrorResult.faceError());
        }
        //人像上传
        String picUrl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        //解析token
        User user = findUserByToken(token);
        //补全userInfo信息
        UserInfo userInfo = new UserInfo();
        userInfo.setId(user.getId());//用户id
        userInfo.setAvatar(picUrl);//用户头像
        userInfo.setCoverPic(picUrl);//用户封面
        //调用rpc更新
        userInfoService.update(userInfo);
        return ResponseEntity.ok(null);

    }

    //根据id查询用户信息
    public ResponseEntity findById(Long userID) {
        //根据userID查询userInfo消息
        UserInfo userInfo = userInfoService.findById(userID);

        //对接前端，使用userInfoVo
        UserInfoVo vo = new UserInfoVo();
        //封装vo
        BeanUtil.copyProperties(userInfo,vo);

        //返回前端
        return ResponseEntity.ok(vo);
    }

    //更新用户信息
    public void updateUserInfo(UserInfo userInfo) {
        //调用rpc修改
        userInfoService.update(userInfo);
    }
}
